package org.epidroid.epidroid.androsoul.ui.contactlist;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.contacts.ContactGroup;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulService;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

public class MoveContactHandler {

	IAndroSoulService _service = null;
	AndroSoulActivity _context = null;

	public MoveContactHandler(IAndroSoulService service,
			AndroSoulActivity context) {
		_service = service;
		_context = context;
	}

	public void showDialog(final NetsoulContact contact) {
		AlertDialog.Builder alert = new AlertDialog.Builder(_context);
		alert.setTitle(_context.getString(R.string.group_change) + " " + contact.getName());
		LayoutInflater factory = LayoutInflater.from(_context);
		final View alertDialogView = factory.inflate(
				R.layout.androsoul_move_contact, null);
		alert.setView(alertDialogView);

		ListView list = (ListView) alertDialogView
				.findViewById(R.id.moveContactGroupList);
		final CheckListAdapter adapter = new CheckListAdapter(_context,
				R.layout.androsoul_list_item_checkbox, _service.getGroupsList(),
				_service.getContactGroups(contact));
		list.setAdapter(adapter);

		alert.setPositiveButton(_context.getString(R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				onOkClick(dialog, whichButton, alertDialogView, adapter,
						contact);
			}
		});
		alert.setNegativeButton(_context.getString(R.string.cancel), null);
		alert.show();
	}

	private void onOkClick(DialogInterface dialog, int whichButton,
			View dialogView, CheckListAdapter adapter, NetsoulContact contact) {
		ArrayList<String> groups = adapter.getSelectedItems();
		List<ContactGroup> all = adapter.getItems();

		if (groups.isEmpty()) {
			// TODO: do not close the window when this happens
			_context.showToast(_context.getString(R.string.group_select));
			return;
		}

		Iterator<ContactGroup> it = all.iterator();
		while (it.hasNext()) {
			ContactGroup item = it.next();
			if (groups.contains(item.getName())) {
				_service.addContact(contact.getName(),
						_service.getGroupFromName(item.getName()));
			} else {
				_service.deleteContact(contact, item);
			}
		}

		_context.saveContacts();
		_context.updateContactsListAdapter();

		_context.showToast(_context.getString(R.string.group_changed));
	}

}
